<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <div class="search-container">
        <div class="search-label">楼宇名称：</div>
        <el-input
          placeholder="请输入内容"
          class="search-main"
          v-model="params.name"
        />
        <div
          class="search-label"
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="success" @click="addBuilding">添加楼宇</el-button>
          <el-button
            type="text"
            @click="exportToExcel"
            style="margin-left: 80px"
            >导出excel</el-button
          >
        </div>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="buildingList">
        <el-table-column type="index" label="序号" :index="indexMethod()" />
        <el-table-column label="楼宇名称" width="180" prop="name" />
        <el-table-column label="层数" prop="floors" width="120" />
        <el-table-column label="在管面积(m²)" width="120" prop="area" />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">租赁中</el-tag>
            <el-tag v-else>空置</el-tag>
            <!-- <el-tag>{{ scope.row.status === 1 ? "租赁中" : "空置" }}</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column label="操作" style="text-align: center">
          <template #default="scope">
            <el-button size="mini" type="text" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="delBuilding(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-size="params.size"
      layout="total, prev,pager, next"
      :total="total"
      style="text-align: center; margin: 30px auto"
    >
    </el-pagination>
    <el-dialog
      :close-on-click-modal="false"
      title="添加楼宇"
      :visible="dialogVisible"
      width="580px"
      @close="cancel"
    >
      <el-form :model="buildInfo" :rules="buildRules" ref="buildForm">
        <el-form-item label="楼宇名称" prop="name">
          <el-input placeholder="请输入楼宇名称" v-model="buildInfo.name" />
        </el-form-item>
        <el-form-item label="层数" prop="floors">
          <el-input placeholder="请输入层数" v-model="buildInfo.floors" />
        </el-form-item>
        <el-form-item label="在管面积" prop="area">
          <el-input placeholder="请输入在管面积" v-model="buildInfo.area" />
        </el-form-item>
        <el-form-item label="物业费单价" prop="propertyFeePrice">
          <el-input
            placeholder="物业费单价"
            v-model="buildInfo.propertyFeePrice"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="mini" @click="cancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitBuilding"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  reqGetBuildingListAPI,
  reqAddBuildingAPI,
  reqDelBuildingAPI,
  reqEditBuildingAPI,
} from "@/api/building.js";
import { utils, writeFileXLSX } from "xlsx";
export default {
  name: "Building",
  data() {
    return {
      params: {
        name: "",
        page: 1,
        size: 10,
      },
      total: 0,
      buildingList: [],
      dialogVisible: false,
      buildInfo: {
        name: "",
        floors: null,
        area: null,
        propertyFeePrice: null,
      },
      buildRules: {
        name: [{ required: true, message: "请填写楼栋名称", trigger: "blur" }],
        floors: [{ required: true, message: "请填写楼层", trigger: "blur" }],
        area: [{ required: true, message: "请填写在管面积", trigger: "blur" }],
        propertyFeePrice: [
          { required: true, message: "请填写物业费单价", trigger: "blur" },
        ],
      },
      obj: {},
    };
  },
  created() {
    this.getBuilding();
  },
  methods: {
    async getBuilding() {
      const res = await reqGetBuildingListAPI(this.params);
      console.log(res);
      this.buildingList = res.data.rows;
      this.total = res.data.total;
    },
    handleSizeChange(e) {
      console.log(e);
      this.params.size = e;
      this.getBuilding();
    },
    handleCurrentChange(e) {
      this.params.page = e;
      this.getBuilding();
    },
    // 格式化序号
    indexMethod() {
      return (this.params.page - 1) * this.params.size + 1;
    },
    search() {
      // 每次搜索，页码必须重置为1
      this.params.page = 1;
      this.getBuilding();
    },
    // 添加楼宇 的回调，需要先清除一下info里面的id，否则会进入编辑页面
    addBuilding() {
      delete this.buildInfo.id;
      this.dialogVisible = true;
    },
    // 提交
    submitBuilding() {
      this.$refs.buildForm.validate(async (flag) => {
        if (!flag) {
          this.$message.error("请填写完整信息");
          return;
        }
        //提交接口,判定是否有id区分新增还是删除
        if (this.buildInfo.id) {
          await reqEditBuildingAPI(this.buildInfo);
          this.$message.success("修改成功");
        } else {
          await reqAddBuildingAPI(this.buildInfo);
          this.$message.success("新增成功");
        }
        this.dialogVisible = false;
        this.$refs.buildForm.resetFields();
        this.getBuilding();
      });
    },
    // 取消
    cancel() {
      this.dialogVisible = false;
      this.$refs.buildForm.resetFields();
      delete this.buildInfo.id;
    },
    // 删除楼宇
    delBuilding(id) {
      this.$confirm("此操作将永久删除该条目, 是否继续?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await reqDelBuildingAPI(id);
        console.log(res);
        this.$notify.success("删除成功!");
        this.getBuilding();
      });
    },
    // 编辑
    edit(building) {
      console.log(building);
      this.dialogVisible = true;
      // 2. 解构必要字段
      const { id, area, floors, name, propertyFeePrice } = building;
      this.buildInfo = {
        id,
        area,
        floors,
        name,
        propertyFeePrice,
      };
    },
    // excel导出
    async exportToExcel() {
      const res = await reqGetBuildingListAPI(this.params);
      const tableHeader = [
        "name",
        "floors",
        "area",
        "propertyFeePrice",
        "status",
      ];
      // 处理数据保证
      const sheetData = res.data.rows.map((item) => {
        const _item = {};
        tableHeader.forEach((key) => {
          _item[key] = item[key];
        });
        console.log(_item);
        return _item;
      });
      console.log(sheetData);
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData);
      // 创建一个新的工作簿
      const workbook = utils.book_new();
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, "Data");
      // 改写表头
      utils.sheet_add_aoa(
        worksheet,
        [["楼宇名称", "层数", "在管面积(㎡)", "物业费(㎡)", "状态"]],
        { origin: "A1" }
      );
      writeFileXLSX(workbook, "SheetJSVueAoO.xlsx");
      console.log("导出成功");
      this.$message.success("导出成功");
    },
  },
};
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}
.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-label {
    width: 100px;
  }
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
</style>
